//
// Created by zzj on 2024/12/21.
//

#include "SqliteDao.h"
#include <QDebug>

SqliteDao::~SqliteDao()
{
    db.close();
}

void SqliteDao::InitDataBase()
{
    if (QString connectionName = "qt_sql_default_connection"; QSqlDatabase::contains(connectionName)) {
        db = QSqlDatabase::database(connectionName);
    } else {
        db = QSqlDatabase::addDatabase("QSQLITE");
    }

    db.setDatabaseName("AnimationUpdate.db");
    if (!db.open()) {
        qDebug() << "Open SQLite failed!";
    }
}

void SqliteDao::InitTable(const QString &videoTableName)
{
    QSqlQuery query;
    const QString existSQL = QString("select count(*) from sqlite_master where type='table' and name='%1'").arg(
        videoTableName);
    query.exec(existSQL);

    if (query.next()) {
        if (query.value(0).toInt() == 0) {
            // 表不存在
            // 构建创建数据库的sql语句字符串
            const QString partialFieldWeekSql =
                    "Mon int DEFAULT -1, Tue int DEFAULT -1, Wed int DEFAULT -1, Thu int DEFAULT -1, Fri int DEFAULT -1, Sat int DEFAULT -1, Sun int DEFAULT -1, Note TEXT)";
            const QString createSql =
                    "CREATE TABLE " + videoTableName +
                    " (id INTEGER PRIMARY KEY AUTOINCREMENT, update_time float DEFAULT 0.0, play_name TEXT NOT NULL, read_episode int DEFAULT 0, update_episode int DEFAULT 0, all_episodes int DEFAULT 0, "
                    +
                    partialFieldWeekSql;

            query.prepare(createSql);
            // 执行sql语句
            if (query.exec()) {
                qDebug() << QString("%1 Table created!").arg(videoTableName);
            } else {
                qDebug() << "Error: Fail to create table. " << query.lastError();
            }
        } else {
            // 表存在
            qDebug() << QString("%1 Table already existed!").arg(videoTableName);
        }
    }
}

int SqliteDao::QueryCount(const QString &sql)
{
    QSqlQuery query;
    if (query.exec(sql)) {
        if (query.next()) {
            const int count = query.value(0).toInt();
            return count;
        }
    }
    qDebug() << "查询失败[QueryCount]：" << query.lastError().text();
    return -1;
}

QList<tuple_record> SqliteDao::QueryRecords(const QString &sql)
{
    QList<tuple_record> resultList;
    QSqlQuery query;
    query.exec(sql);

    while (query.next()) {
        auto tmpTuple = std::make_tuple(
            query.value("id").toInt(),
            query.value("update_time").toFloat(),
            query.value("play_name").toString(),
            query.value("read_episode").toInt(),
            query.value("update_episode").toInt(),
            query.value("all_episodes").toInt(),
            query.value("Mon").toLongLong(),
            query.value("Tue").toLongLong(),
            query.value("Wed").toLongLong(),
            query.value("Thu").toLongLong(),
            query.value("Fri").toLongLong(),
            query.value("Sat").toLongLong(),
            query.value("Sun").toLongLong(),
            query.value("Note").toString()
        );
        resultList.push_back(tmpTuple);
    }
    return resultList;
}

bool SqliteDao::Upgrade(const int id, const QString &tableName, const QString &fieldName, const QString &fieldValue)
{
    const QString updateSql = "UPDATE " + tableName + " SET " + fieldName + " = " + fieldValue + " WHERE id = " +
                              QString::number(id) + ";";
    QSqlQuery query;
    if (query.exec(updateSql)) {
        return true;
    }
    qDebug() << "更改失败：" << query.lastError().text();
    return false;
}
